# coding=utf-8

from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
import time
from multiprocessing import Process
import logging
import multiprocessing
from components.logger import logger
from managers import app_config


def schedule_task(func):
    def wrapper(*args, **kwargs):

        func_wrap = lambda: func(*args, **kwargs)
        taskname = args[1][1] + '(' + args[1][0] + ')' + func.__name__

        def task():
            logger.info("当前进程的id" + str(multiprocessing.current_process().pid))
            logger.info("定时任务" + taskname + "开始执行")
            logger.debug("入参:" + str(args) + str(kwargs))

            logging.basicConfig(level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                                datafmt='%a, %d %b %Y %H:%M:%S',
                                filename='./output/logs/task_' + taskname + '_' + str(datetime.now()) + '.log',
                                filemode='a')

            if not app_config.env:
                func_wrap()

            scheduler = BackgroundScheduler()
            # scheduler.add_job(func_wrap, 'interval', seconds=1200)
            # mon,tue,wed,thu,fri,sat,sun
            scheduler.add_job(func_wrap, 'cron', day_of_week="mon,tue,wed,thu,fri,sat,sun", hour=0)
            scheduler.start()

            try:
                while True:
                    time.sleep(10)
            except (KeyboardInterrupt, SystemExit):
                scheduler.shutdown()

        task()

        # p = Process(target=task, name=taskname)
        # logger.info("定时任务" + func.__name__ + "进程1")
        # p.daemon = True
        # p.start()
        # p.join()
        # logger.info("定时任务" + func.__name__ + "进程2" + str(p.pid()))

    return wrapper


@schedule_task
def tick(a, b):
    print('Tick! The time is: %s' % datetime.now())
    print a
    print b


if __name__ == '__main__':
    tick("1", "2")
    # scheduler = BackgroundScheduler()
    # scheduler.add_job(tick, 'interval', seconds=3)
    # scheduler.start()
    # print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # try:
    #     # This is here to simulate application activity (which keeps the main thread alive).
    #     while True:
    #         time.sleep(2)
    # except (KeyboardInterrupt, SystemExit):
    #     # Not strictly necessary if daemonic mode is enabled but should be done if possible
    #     # scheduler.shutdown()
    #     pass
